import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:typed_data';

class TestUploadPage extends StatefulWidget {
  const TestUploadPage({super.key});

  @override
  State<TestUploadPage> createState() => _TestUploadPageState();
}

class _TestUploadPageState extends State<TestUploadPage> {
  String _publicUrl = '';
  Uint8List? _selectedFile;
  String? _fileName;

  // 选择文件方法
  Future<void> _pickFile() async {
    final pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    
    if (pickedFile != null) {
      final bytes = await pickedFile.readAsBytes();
      setState(() {
        _selectedFile = bytes;
        _fileName = pickedFile.name; // 保存原始文件名
      });
    }
  }

  // 上传文件方法（关键修正）
    Future<void> _uploadFile() async {
    if (_selectedFile == null || _fileName == null) return;

try {
  // 只保留英文、数字、下划线和点
  String safeFileName = _fileName!
      .replaceAll(RegExp(r'[^\w\.-]'), '_'); // 替换非法字符为下划线

  final fileName = 'public_${DateTime.now().millisecondsSinceEpoch}_$safeFileName';

  await Supabase.instance.client.storage
      .from('storagegb')
      .uploadBinary(fileName, _selectedFile!);

  final url = Supabase.instance.client.storage
      .from('storagegb')
      .getPublicUrl(fileName);

  setState(() => _publicUrl = url);
  debugPrint('✅ 上传成功: $url');
} catch (e) {
  debugPrint('❌ 上传失败: $e');
}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('文件上传测试')),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _pickFile,
              child: const Text('选择文件'),
            ),
            const SizedBox(height: 20),
            if (_fileName != null) // ✅ 显示文件名而非路径
              Text('已选择文件: $_fileName'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _uploadFile,
              child: const Text('上传文件'),
            ),
            const SizedBox(height: 20),
            if (_publicUrl.isNotEmpty)
              SelectableText('文件链接: $_publicUrl'),
          ],
        ),
      ),
    );
  }
}